package com.zzyl.nursing.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.FamilyMemberData;
import com.zzyl.nursing.dto.FamilyOrElderDto;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.*;

import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.IWechatService;
import com.zzyl.nursing.vo.LoginVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
@RequiredArgsConstructor
public class FamilyMemberServiceImpl implements IFamilyMemberService {

    private final IWechatService wechatService;
    private final FamilyMemberMapper familyMemberMapper;
    private final TokenService tokenService;
    private final ElderMapper elderMapper;
    private final FamilyMemberElderMapper familyMemberElderMapper;
    private final BedMapper bedMapper;
    private final RoomMapper roomMapper;

    @Override
    public LoginVo login(UserLoginRequestDto dto) {
        //1.获取openid
        String openId = wechatService.getOpenId(dto.getCode());
        //2.通过openid去数据库里看看有没有,
        FamilyMember familyMember = familyMemberMapper.selectOne(Wrappers.<FamilyMember>lambdaQuery().eq(FamilyMember::getOpenId, openId));
        if (familyMember == null){
            log.info("该用户是新用户,需要获取手机号,并保存到DB中");
            //3.获取手机号,存到DB中
            String phone = wechatService.getPhone(dto.getPhoneCode());
            familyMember = new FamilyMember();
            familyMember.setName("花开富贵");
            familyMember.setOpenId(openId);
            familyMember.setPhone(phone);
            familyMember.setCreateTime(new Date());
            familyMemberMapper.insert(familyMember);
        }
        //4.生成token
        Map<String,Object> map = new HashMap<>();
        map.put("id",familyMember.getId());
        map.put("openId",openId);
        String token = tokenService.copyCreateToken(map);
        //5.封装返回
        LoginVo loginVo = new LoginVo();
        loginVo.setNickName("富贵花开");
        loginVo.setToken(token);
        return loginVo ;
    }

    /**
     * 绑定家人
     * @param elderFamilyAddDto
     */
    @Override
    public void addFamily(FamilyOrElderDto elderFamilyAddDto) {
        //获取到老人身份证号
        String idCard = elderFamilyAddDto.getIdCard();
        //根据身份证号去数据进行比对,判断是否是养老院老人
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, idCard));
        if (elder == null){
            throw new RuntimeException("该老人不是养老院老人");
        }
        //从线程池副本中获取到当前登录用户的id
        Long userId = UserThreadLocal.getUserId();

        //将用户id和老人id绑定在一起,保存到新对象中
        com.zzyl.nursing.domain.FamilyMemberElder familyMemberElder = new com.zzyl.nursing.domain.FamilyMemberElder();
        familyMemberElder.setElderId(elder.getId());
        familyMemberElder.setFamilyMemberId(userId);
        familyMemberElder.setRemark(elderFamilyAddDto.getRemark());
        familyMemberElderMapper.insert(familyMemberElder);
    }

    @Override
    public List<FamilyMemberElder> getFamily() {
        //获取到当前登录用户的id
        Long userId = UserThreadLocal.getUserId();
        if (userId == null){
            throw new RuntimeException("用户未登录");
        }
        List<FamilyMemberElder> familyMemberElders = familyMemberElderMapper.selectList(Wrappers.<FamilyMemberElder>lambdaQuery().eq(FamilyMemberElder::getFamilyMemberId, userId));
        for (FamilyMemberElder familyMemberElder : familyMemberElders) {
            Long elderId = familyMemberElder.getElderId();
            Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getId, elderId));
            familyMemberElder.setElderName(elder.getName());
        }
        return familyMemberElders;
    }

    @Override
    public List<FamilyMemberData> listByPage(Integer pageNum, Integer pageSize) {
        //创建返回对象
        ArrayList<FamilyMemberData> familyMemberData = new ArrayList<>();
        //获取当前登录用户的id
        Long userId = UserThreadLocal.getUserId();
        //开启分页
        PageHelper.startPage(pageNum, pageSize);
        //获取到当前登录用户的所有老人
        List<FamilyMemberElder> familyMemberElderList = familyMemberElderMapper.selectList(Wrappers.<FamilyMemberElder>lambdaQuery().eq(FamilyMemberElder::getFamilyMemberId, userId));
        for (FamilyMemberElder familyMemberElder : familyMemberElderList) {
            //创建对象接受参数
            FamilyMemberData familyData  = new FamilyMemberData();
            //获取表的id
            Long mid = familyMemberElder.getId();
            familyData.setMid(mid);
            //获取老人的id
            Long elderId = familyMemberElder.getElderId();
            familyData.setElderId(elderId);
            //取出老人称呼
            String remark = familyMemberElder.getRemark();
            familyData.setMremark(remark);
            //获取老人的信息
            Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getId, elderId));
            familyData.setName(elder.getName());
            familyData.setImage(elder.getImage());
            //获取房间号,一会需要来查房间信息
            String bedNumber = elder.getBedNumber();
            familyData.setBedNumber(bedNumber);
            Bed bed = bedMapper.selectOne(Wrappers.<Bed>lambdaQuery().eq(Bed::getBedNumber, bedNumber));
            Long roomId = bed.getRoomId();
            Room room = roomMapper.selectOne(Wrappers.<Room>lambdaQuery().eq(Room::getId, roomId));
            familyData.setTypeName(room.getTypeName());
            //根据用户id获取设备信息
            familyData.setIotId(null);
            familyData.setDeviceName(null);
            familyData.setProductKey(null);
            familyMemberData.add(familyData);
        }
        return familyMemberData;
    }


    @Override
    public int deleteById(Long id) {
        return familyMemberElderMapper.deleteById(id);
    }


}
